<template>
  <div>
    <Modal v-model="modal.show"  :title="modal.title"  :mask-closable="false" :footer-hide=true width="1080px" :closable="false">
      <SearchHeader v-model="table.param.where.keyword" :canAdd="selects" :addBtnTitle="addBtnTitle" @handleAdd="add" @handleSearch="getData"  @handleInit="init">
        <Row :gutter="4">
          <Col span="6"><Input clearable :placeholder="$t('device_code')" v-model="table.param.where.code"></Input> </Col>
          <Col span="6"><Input clearable :placeholder="$t('device_name')" v-model="table.param.where.name"></Input> </Col>
          <Col span="6"><UserModelSelect ref="srhUserSelect" width="100%" v-model="table.param.where.userId"></UserModelSelect> </Col>
          <Col span="6"><OrganizationTree v-model="table.param.where.orgId" ref="organization" width="200px"/> </Col>
        </Row>
      </SearchHeader>
      <Card>
        <Table border ref="device5gTable" :columns="table.columns" :data="table.data" :loading="table.loading" @on-row-click="rowclick" @on-selection-change="onSelectionChange">
        </Table>
        <TopnavPage v-model="table.param.page" @changePage="changePage"></TopnavPage>
      </Card>
      <Form>
        <FormItem>
          <div style="float: right;">
            <Button @click="close">{{$t('close')}}</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import TopnavPage from '_c/topnav/TopnavPage'
import OrganizationTree from '@/components/topnav/OrganizationTree';
import UserModelSelect from '@/components/topnav/UserModelSelect';
import SearchHeader from "@/view/Common/SearchHeader";
import Device from "@/api/Device";
import Zzd from '@/api/Zzd';
import {apiResult} from "@/libs/util";
export default {
  name: "ZzdDevice5gSelect",
  components:{TopnavPage,OrganizationTree,UserModelSelect,SearchHeader},
  data(){
    return{
      api: new Device(),
      zzpApi: new Zzd(),
      modal:{
        show:false,
        title:this.$t('device_manage')
      },
      table:{
        loading:false,
        param:{
          page:{pages: 1,size: 10,total: 0, current: 1,},
          where:{keyword:null,code:null,name:null,cate:2,userId:null,orgId:null},
        },
        columns:[
          {type: 'selection',width:60,align:'center'},
          {title: this.$t('device_code'), key: 'code', sortable: true, width: 250,ellipsis:true,tooltip:true,tooltipTheme:'light'},
          {title: this.$t('imei_code'), key: 'imeiCode', sortable: true, width: 150,ellipsis:true,tooltip:true,tooltipTheme:'light'},
          {title: this.$t('talk_account'), key: 'talkAccount', sortable: true, width: 150,ellipsis:true,tooltip:true,tooltipTheme:'light'},
          {title: this.$t('device_name'), key: 'name', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
          {title: this.$t('user_name'), key: 'userName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
          {title: this.$t('organization_name'), key: 'orgName', sortable: true, width: 200,ellipsis:true,tooltip:true,tooltipTheme:'light'},
        ],
        data:[],
        selection:[],
      },
      callBack:null,
      addBtnTitle: this.$t('device_reg_talk_user'),
      selects:false,
      groupId:null,
      regiseredUsers:[],
    }
  },
  methods:{
    /**
     * 把选择的用户加入到第三方系统
     */
    add(){
      if (!this.table.selection || this.table.selection.length===0){
        this.$Message.error(this.$t('no_select_data'))
        return;
      }

      let params = [];
      this.table.selection.forEach((item)=>{
        console.log(item);
        let talkAccount = !!item.talkAccount ? item.talkAccount:null;
        talkAccount = !!talkAccount?talkAccount:item.imeiCode.length >= 14?item.imeiCode.substr(7,7):item.imeiCode
        if (!!item.imeiCode){
          params.push(
            {
              userId:item.talkId,
              userAccount:talkAccount,
              userName:item.name,
              deviceId:item.id,
              groupId:this.groupId,
              registered:  item.disabled === true//!!item.talkAccount
            })
        }
      })
      if(params.length === 0){
        return;
      }
/*      console.log(params);
      return;*/

      const msg = this.$Message.loading({content: this.$t('wait_dispose_message'),duration: 10});
      this.zzpApi.registUserOrAndGroup(JSON.stringify(params)).then(res=>{
        setTimeout(msg, 100); //关闭正加载条
        this.$refs.device5gTable.selectAll(false);
        console.log("ZzdDevice5gSelect.add: res=%o",res)
          apiResult(res.data,true,data1=>{
            const result = data1.data;
            const msg = this.$t('submit')+": "+result.total +"; "+this.$t('succeed') + ": "+result.successCount + "; " + this.$t('fialure') + ": " + result.failedCount;
            if (result.failedCount > 0){
              this.$Message.error({
                content: msg,
                duration: 5,
                closable: true
              })
              this.$Message.error({
                content: result.msgs,
                duration: 10,
                closable: true
              })
            }else{
              this.$Message.success(msg);
            }
          })
        this.refreshData();
      });
    },
    onSelectionChange(selection){
      console.log(selection)
      this.selects = !!selection && selection.length > 0;
      this.table.selection = selection;
    },
    rowclick(row){},
    changePage(){this.getData()},
    init(){},
    openDialog(groupId,callBack){
      //console.log("ZzdDevice5gSelect.openDialog()：groupId=%o", groupId)
      this.groupId=groupId;
      this.modal.show=true;
      this.callBack = callBack;
      this.refreshData();
    },
    refreshData(){
      this.zzpApi.findUserByGroup(this.groupId).then(res => {
        apiResult(res.data,false,result=> {
          console.log("ZzdDevice5gSelect.openDialog()：findUserByGroup.result=%o", result)
          this.regiseredUsers = result.data
          this.getData();
        });
      });
    },
    getData(){
      /** 生成查询条件 */
      console.log("ZzdDevice5gSelect.getData()")
      this.table.loading =true;
      this.api.queryPage(JSON.stringify(this.table.param)).then(res => {
        this.table.loading =false;
        apiResult(res.data,false,result=> {
          this.table.data = result.data.records;
          this.table.param.page.total = res.data.data.total;
          console.log("ZzdDevice5gSelect.getData(): table.data=%o",this.table.data)
          console.log("ZzdDevice5gSelect.getData(): regiseredUsers=%o",this.regiseredUsers)
          this.table.data.forEach((device)=>{
            device["_disabled"] = false;
            this.regiseredUsers.forEach((user)=>{
              let o="ds";
              //已注册且在这个群组里则变灰
              if (!!device.talkAccount && device.talkAccount === user.userAccount){
                user.groupIds.split().some((grpId)=>{
                  if (grpId===this.groupId){
                    device["_disabled"] = true;
                  }
                })
              }
            })
            //没有imei码变灰
            if (!device.imeiCode){
              device["_disabled"] = true;
            }
          });
        })
      })
    },
    close(){
      this.modal.show = false;
      if (!!this.callBack){
        this.callBack();
      }
    },
    mounted(){
      this.addBtnTitle= this.$t('device_reg_talk_user');
    }
  }
}

</script>
<style>

</style>
